package edu.chl.jadetalk.db;

import edu.chl.jadetalk.core.Comment;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author Daniel
 */
@Stateless
public class CommentFacade implements ICommentFacade {

    @PersistenceContext(unitName = "jadetalk_pu")
    private EntityManager em;

    @Override
    public void create(Comment comment) {
        em.persist(comment);
    }

    @Override
    public void edit(Comment comment) {
        em.merge(comment);
    }

    @Override
    public void remove(Comment comment) {
        em.remove(em.merge(comment));
    }

    @Override
    public Comment find(Object id) {
        return em.find(Comment.class, id);
    }

    @Override
    public List<Comment> findAll() {
        CriteriaQuery<Comment> cq = em.getCriteriaBuilder().createQuery(Comment.class);
        cq.select(cq.from(Comment.class));
        return em.createQuery(cq).getResultList();
    }

    @Override
    public List<Comment> findRange(int[] range) {
        CriteriaQuery<Comment> cq = em.getCriteriaBuilder().createQuery(Comment.class);
        cq.select(cq.from(Comment.class));
        TypedQuery<Comment> q = em.createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }
    
    

    @Override
    public int count() {
        CriteriaQuery<Long> cq = em.getCriteriaBuilder().createQuery(Long.class);
        Root<Comment> rt = cq.from(Comment.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        TypedQuery<Long> q = em.createQuery(cq);
        return (q.getSingleResult()).intValue();
    }
    
    /**
     * For testing purposes.
     * @param em 
     */
    void setEm(EntityManager em) {
        this.em = em;
    }
}
